// //模拟
// function spiralOrder(matrix) {
//     if (!matrix.length || !matrix[0].length) return []

//     const rows = matrix.length
//     const colums = matrix[0].length
//     const visited = new Array(rows).fill(0).map(() => new Array(colums).fill(false))
//     const total = rows * colums
//     const order = new Array(total).fill(0)

//     let directionIndex = 0
//     let row = 0, colum = 0
//     const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
//     for (let i = 0; i < total; i++) {
//         order[i] = matrix[row][colum]
//         visited[row][colum] = true
//         const nextRow = row + directions[directionIndex][0]
//         const nextColum = colum + directions[directionIndex][1]
//         //下个遍历元素在范围内且未visited，不需要转向，否则转
//         if (!(0 <= nextRow && nextRow < rows && 0 <= nextColum && nextColum < colums && !(visited[nextRow][nextColum]))) {
//             directionIndex = (directionIndex + 1) % 4
//         }
//         console.log(directionIndex)
//         row = row + directions[directionIndex][0]
//         colum = colum + directions[directionIndex][1]
//     }
//     return order
// }



//逐层模拟
function spiralOrder(matrix) {
    if (!matrix.length || !matrix[0].length) return []

    const rows = matrix.length
    const colums = matrix[0].length
    const order = []
    let left = 0, right = colums - 1, top = 0, bottom = rows - 1
    while (left <= right && top <= bottom) {
        //遍历该层顶行
        for (let colum = left; colum <= right; colum++) {
            order.push(matrix[top][colum])
        }
        for (let row = top + 1; row <= bottom; row++) {
            order.push(matrix[row][right])
        }
        if (left < right && top < bottom) {
            for (let colum = right - 1; colum > left; colum--) {
                order.push(matrix[bottom][colum])
            }
            for (let row = bottom; row > top; row--) {
                order.push(matrix[row][left])
            }
        }
        [left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1]
    }
    return order
}

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(spiralOrder(data))